package controllers

import (
	json2 "encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"goods-mnger/cache"
	"goods-mnger/models"
	"time"
)

type ShopController struct {
	beego.Controller
}

type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopController) Add() {
	name := c.GetString("name")
	res := c.GetString("res")
	address := c.GetString("address")
	price := c.GetString("price")
	shop := models.Shop{
		Name:    name,
		Res:     res,
		Address: address,
		Price:   price,
	}
	err := models.DB.Create(&shop).Error
	data := "data_add"
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, data).Result()
	if cacheJson == "" {
		json, _ := json2.Marshal(shop)
		cache.Rdb.Set(cache.Ctx, data, json, time.Hour*2)
	} else {
		json2.Unmarshal([]byte(cacheJson), &shop)
		fmt.Println("缓存成功")
	}
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "添加成功",
		Data: shop,
	}
	c.ServeJSON()
	return
}

func (c *ShopController) List() {
	var shop []models.Shop
	models.DB.Find(&shop)
	data := "data_list"
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, data).Result()
	if cacheJson == "" {
		json, _ := json2.Marshal(shop)
		cache.Rdb.Set(cache.Ctx, data, json, time.Hour*2)
	} else {
		json2.Unmarshal([]byte(cacheJson), &shop)
		fmt.Println("缓存成功")
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "查询成功",
		Data: shop,
	}
	c.ServeJSON()
	return
}

func (c *ShopController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	res := c.GetString("res")
	address := c.GetString("address")
	price := c.GetString("price")
	shop := models.Shop{
		Name:    name,
		Res:     res,
		Address: address,
		Price:   price,
	}
	err := models.DB.Where("id=?", id).Updates(&shop).Error
	data := "data_add"
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, data).Result()
	if cacheJson == "" {
		json, _ := json2.Marshal(shop)
		cache.Rdb.Set(cache.Ctx, data, json, time.Hour*2)
	} else {
		json2.Unmarshal([]byte(cacheJson), &shop)
		fmt.Println("缓存成功")
	}
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "修改成功",
		Data: shop,
	}
	c.ServeJSON()
	return
}

func (c *ShopController) Del() {
	id, _ := c.GetInt("id")
	var shop models.Shop
	models.DB.Delete(&shop, id)
	data := "data_del"
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, data).Result()
	if cacheJson == "" {
		json, _ := json2.Marshal(shop)
		cache.Rdb.Set(cache.Ctx, data, json, time.Hour*2)
	} else {
		json2.Unmarshal([]byte(cacheJson), &shop)
		fmt.Println("缓存成功")
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "删除成功",
	}
	c.ServeJSON()
	return
}
